<?php
/**
 * 数据库连接和商品分类数据测试
 */

// 引入框架
require_once __DIR__ . '/backend/vendor/autoload.php';
require_once __DIR__ . '/backend/support/bootstrap.php';

use app\model\GoodsCatModel;

echo "=== 数据库连接测试 ===\n";

try {
    // 测试数据库连接
    $categories = GoodsCatModel::all();
    
    echo "数据库连接成功！\n";
    echo "商品分类总数: " . $categories->count() . "\n\n";
    
    if ($categories->count() > 0) {
        echo "=== 现有分类数据 ===\n";
        foreach ($categories as $category) {
            echo "ID: {$category->id}, Name: {$category->name}, FID: {$category->fid}, Sort: {$category->sort}\n";
        }
        
        echo "\n=== 转换为数组 ===\n";
        $categoriesArray = $categories->toArray();
        echo json_encode($categoriesArray, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";
        
    } else {
        echo "数据库中没有商品分类数据\n";
        
        // 插入测试数据
        echo "\n=== 插入测试数据 ===\n";
        
        $testData = [
            ['name' => '电子产品', 'fid' => 0, 'sort' => 1],
            ['name' => '手机', 'fid' => 1, 'sort' => 1],
            ['name' => '电脑', 'fid' => 1, 'sort' => 2],
            ['name' => '服装', 'fid' => 0, 'sort' => 2],
            ['name' => '男装', 'fid' => 4, 'sort' => 1],
            ['name' => '女装', 'fid' => 4, 'sort' => 2],
        ];
        
        foreach ($testData as $data) {
            $category = new GoodsCatModel();
            $category->name = $data['name'];
            $category->fid = $data['fid'];
            $category->sort = $data['sort'];
            $category->status = 1;
            $category->created_at = time();
            $category->updated_at = time();
            $category->save();
            
            echo "插入分类: {$data['name']} (ID: {$category->id})\n";
        }
        
        echo "\n=== 重新查询数据 ===\n";
        $newCategories = GoodsCatModel::all();
        foreach ($newCategories as $category) {
            echo "ID: {$category->id}, Name: {$category->name}, FID: {$category->fid}, Sort: {$category->sort}\n";
        }
    }
    
} catch (Exception $e) {
    echo "数据库连接失败: " . $e->getMessage() . "\n";
} 